//
//  HMRefreshControl.swift
//  01-SinaWeibo
//
//  Created by 周英培 on 16/5/27.
//  Copyright © 2016年 周英培. All rights reserved.
//

import SnapKit

//定义枚举 设置三种状态
enum RefreshStatue: Int{
    case Normal     //普通状态
    case Pulling    //准备刷新状态
    case Refreshing //正在刷新
}

private let refreshViewHeight: CGFloat = 60

//UIControl 是控件 所以可以被触发  能够发送消息
class HMRefreshControl: UIControl {
    
    //三种状态
    var statue : RefreshStatue = .Normal {
    
        didSet {
        
            switch statue {
            case .Normal:
                print("下拉起飞")
                
                //设置状态下的文字
                tipLabel.text = "下拉起飞"
                
                //显示箭头
                arrowicon.hidden = false
                
                //停止转动小菊花
                indicatorView.stopAnimating()
                
                UIView.animateWithDuration(0.25, animations: { 
                    
                    //设置状态下的箭头 并且加上动画
                    self.arrowicon.transform = CGAffineTransformIdentity
                })
               
                
            case .Pulling:
                print("准备起飞")
                tipLabel.text = "准备起飞"
                
                UIView.animateWithDuration(0.25, animations: { 
                    
                    self.arrowicon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                
            case .Refreshing:
                print("正在起飞")
                tipLabel.text = "正在起飞"
                
                //隐藏箭头
                arrowicon.hidden = true
                
                //转动小菊花
                indicatorView.startAnimating()
                
                //请求网络数据 给观察的对象主动发送对应类型的事件  在这里响应事件的状态要和观察对象的响应事件的状态要一致
                sendActionsForControlEvents(.ValueChanged)
        }
    
    }

}
    
    //停止转动时 恢复普通状态
    func endRefreshing() {
    
    statue = .Normal
    
    }
    
    override init(frame: CGRect) {
        
        //隐藏在导航条下：y: -refreshViewHeight   y:0没有隐藏在导航条下
        let rect = CGRect(x: 0, y: -refreshViewHeight, width: ScreenWidth, height: refreshViewHeight)
        super.init(frame: rect)
//        backgroundColor = UIColor.yellowColor()
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //将要移动到父视图上
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        super.willMoveToSuperview(newSuperview)
        
        //判断 如果是父类是scroller或者使其子类  就获取父视图垂直方向的位移
        //利用KVO 通过键值方式观察对象属性的 变化
       if let fatherView = newSuperview as? UIScrollView {
        
        scrollView = fatherView
        
        //添加观察者 obsetber 观察者   forKeyPath 路径    options 可以观察三个值  context 上下文
        fatherView.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
        
        }
        
    }
    
    //利用KVO必须实现键值观察的响应方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        //获取父视图垂直方向的位移 
        //有个临界点 -124 即导航条的高度＋自定义控件的高度
        //两种情况  被拖拽 没有拖拽  然后三种状态
        let offsetY = scrollView?.contentOffset.y ?? 0
        
        //拖拽状态下
        if scrollView!.dragging {
            
            if statue == .Pulling && offsetY > -124 {
                
                //普通状态
                statue = .Normal
                
            } else if statue == .Normal && offsetY < -124 {
            
               //达到临界点 等待刷新
                statue = .Pulling
                
            }
            
        } else {
        
           //没有拖拽 状态为等待刷新状态 然后修改为刷新状态
            if statue == .Pulling {
                
                statue = .Refreshing
            }
        
        }
        
    }
    
    //移除键值观察
    deinit {
    
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    
    }
    
    private func setupUI() {
        addSubview(arrowicon)
        addSubview(tipLabel)
        addSubview(indicatorView)
        addSubview(backImageView)
        
        arrowicon.snp_makeConstraints { (make) -> Void in
            //水平居中 向左偏移 30
            make.centerX.equalTo(self.snp_centerX).offset(-30)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        tipLabel.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(arrowicon.snp_right)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        
        indicatorView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowicon.snp_center)
        }
        
        backImageView.snp_makeConstraints { (make) in
            make.left.right.bottom.equalTo(self)
        }
    }
    
    //懒加载子视图
    //记录父视图的属性
    var scrollView: UIScrollView?
    private lazy var arrowicon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    private lazy var tipLabel: UILabel = UILabel(title: "下拉起飞", font: 14, textColor: UIColor.darkGrayColor())
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
    
    //添加背景图片
    private lazy var backImageView : UIImageView = UIImageView(image: UIImage(named: "refreshbg"))
    
   
}
